import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QFont, QColor
from dao.classRecord import classRecord
from dao.index import LoginSchema
from utils.json import JSONHandler

class FramelessTable(QWidget):
    def __init__(self):
        super().__init__()
        self.json = JSONHandler("./config/cache.json")
        self.initUI()
        self.loadDemoData()

    def initUI(self):
        # 窗口设置
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setGeometry(100, 100, 640, 480)
        
        # 直接使用窗口作为容器
        self.table = QTableWidget(self)
        self.table.setColumnCount(8)
        self.table.setHorizontalHeaderLabels([
            "序号", "学号", "学生姓名", "考试名称", 
            "班级", "教师", "签到时间", "考试开始时间"
        ])

        # 表格尺寸策略
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        # 样式配置
        self.configureTable()
        
        # 文字居中的委托
        self.table.setItemDelegate(AlignmentDelegate())

    def configureTable(self):
        # 基础设置
        self.table.verticalHeader().setVisible(False)
        self.table.setShowGrid(False)
        self.table.setAlternatingRowColors(True)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # 设置按列选择模式
        self.table.setSelectionBehavior(QAbstractItemView.SelectColumns)

        # 列宽策略
        header = self.table.horizontalHeader()
        header.setDefaultSectionSize(120)
        header.setSectionResizeMode(0, QHeaderView.Fixed)
        header.resizeSection(0, 60)
        header.setSectionResizeMode(1, QHeaderView.Stretch)

        # 现代化样式
        self.table.setStyleSheet('''
            QTableWidget {
                background: #FAFAFA;
                border: none;
                font-family: 'Segoe UI';
                font-size: 13px;
                alternate-background-color: #E6F3FF;  /* 斑马纹颜色 */
            }
            QHeaderView {
                background: transparent;
            }
            QHeaderView::section {
                background: #87CEEB;  /* 表头淡蓝色 */
                color: white;
                padding: 14px 0;
                border: none;
                font-weight: 500;
            }
            QTableWidget::item {
                border-bottom: 1px solid #E0E0E0;
                padding: 12px 0;
                color: #455A64;
            }
            QTableWidget::item:selected {
                background: #87CEEB;  /* 选中列颜色 */
            }
        ''')

        # 字体设置
        self.table.setFont(QFont('Segoe UI', 11))

    def resizeEvent(self, event):
        # 动态调整表格尺寸（包含10px内边距）
        self.table.setGeometry(
            10, 10, 
            self.width()-20, 
            self.height()-20
        )
        super().resizeEvent(event)

    def loadDemoData(self):
        print("aaa")
        user = LoginSchema().get_student(self.json.read()['user_id'])
        class_record = classRecord(). get_record_by_student(user['name'],user['class_name'])
        print(class_record)

        self.table.setRowCount(len(class_record))
        
        # 列映射关系
        column_mapping = [
            ('id', lambda x: str(x)),                # 序号列
            ('student_number', str),                 # 学号列
            ('student_name', str),                   # 学生姓名列
            ('exam_name', str),                     # 考试名称列
            ('exam_class', str),                    # 班级列
            ('teacher_name', str),                   # 教师列
            ('sign_in_time', lambda x: x.strftime("%Y-%m-%d %H:%M:%S")),  # 签到时间
            ('exam_start_time', lambda x: x.strftime("%Y-%m-%d %H:%M"))   # 考试时间
        ]

        # 填充数据
        for row_idx, record in enumerate(class_record):
            for col_idx, (field, formatter) in enumerate(column_mapping):
                value = record.get(field, "")
                try:
                    formatted_value = formatter(value)
                except:
                    formatted_value = str(value)
                
                item = QTableWidgetItem(formatted_value)
                item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row_idx, col_idx, item)

class AlignmentDelegate(QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        option.displayAlignment = Qt.AlignCenter
